package com.example.mytestdemo.widget.demo4;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.TypeEvaluator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Color;
import android.graphics.PointF;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.example.mytestdemo.R;
import com.example.mytestdemo.widget.demo2.DpUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * * Github:https://github.com/MrAllRight
 *
 * @author lfc-LFC
 * created at 2022/9/23 14:19
 */

public class BullbeBeautyView extends RelativeLayout {
    private Drawable[] mDrawables;//装载3中点赞图片，红黄蓝
    private int mDrawableWidth, mDrawableHeight;//图片的宽高
    private Random mRandom = new Random();
    private PointF p0, p1, p2, p3;//控制图片的移动轨迹，通过3阶贝塞尔曲线
    private int screenWidth, screenHeight;//屏幕宽高

    private OnCommonCallBack onCommonCallBack;
    private List<BullbeData> listData = new ArrayList<BullbeData>();
    private Thread mBubbleThread;
    private Context mctx;

    public List<BullbeData> getListData() {
        if (listData == null) {
            return new ArrayList<>();
        }
        return listData;
    }

    public void setListData(List<BullbeData> listData) {
        this.listData = listData;
    }

    public OnCommonCallBack getOnCommonCallBack() {
        return onCommonCallBack;
    }

    public void setOnCommonCallBack(OnCommonCallBack onCommonCallBack) {
        this.onCommonCallBack = onCommonCallBack;
    }

    public BullbeBeautyView(Context context) {
        super(context);
        init(context);
    }

    public BullbeBeautyView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    public BullbeBeautyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        screenHeight = h;
        screenWidth = w;
    }

    //初始化drawable，params
    private void init(Context context) {
    /*    mDrawables = new Drawable[3];
        mDrawables[0] = getResources().getDrawable(R.mipmap.icon_live_light_1);
        mDrawables[1] = getResources().getDrawable(R.mipmap.icon_live_light_2);
        mDrawables[2] = getResources().getDrawable(R.mipmap.icon_live_light_3);
        mDrawableWidth = mDrawables[0].getIntrinsicWidth();
        mDrawableHeight = mDrawables[0].getIntrinsicHeight();*/

    }

    // 主线程
    Handler handler = new Handler();
    // 子线程
//    Handler handler = new Handler(Looper.getMainLooper());
    boolean isViewBackground = false;

    // 开始气泡线程
    private void startBubbleSync() {
        Log.d("xxlfc", "stopBubbleSync");

        stopBubbleSync();
        mBubbleThread = new Thread() {
            public void run() {
                while (!isViewBackground) {
                    try {
                   /*     if (isViewBackground)
                            Thread.sleep(5000);
                        else {
                            Thread.sleep(1000);
                        }*/
                        Thread.sleep(1000);

                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                Log.d("xxlfc", "主线程 ： addGiftIv");
                                addGiftIv();
                            }
                        }, 300);

                    } catch (Exception e) {
                        System.out.println("Bubble线程结束");
                        break;
                    }
                }
            }
        };
        mBubbleThread.start();
    }

    // 停止气泡线程
    private void stopBubbleSync() {
        Log.d("xxlfc", "stopBubbleSync");
        if (null == mBubbleThread)
            return;
        mBubbleThread.interrupt();
        mBubbleThread = null;
    }

    /**
     * 当前列表 index
     */
    private int currentIndex = 0;

    //点击图片是添加imageview到布局中，并添加动画
    private void addGiftIv() {
        final ImageView giftIv = new ImageView(getContext());

        LayoutParams params = new LayoutParams(DpUtil.dp2px(60), DpUtil.dp2px(60));
        params.addRule(ALIGN_PARENT_BOTTOM, TRUE);
        //   实物 或者   气泡
        boolean isBeauty = new Random().nextInt(100) > 45;
        if (isBeauty) {
            params.width = DpUtil.dp2px(new Random().nextInt(10) + 50);
            params.height = params.width;
        } else {
            params.width = DpUtil.dp2px(new Random().nextInt(10) + 40);
            params.height = params.width;
        }

//        params.addRule(CENTER_IN_PARENT, TRUE);
        params.setMargins((int) (screenWidth * (new Random().nextInt(80) + 20) / 100), 0, 0, 30);//放置在屏幕的右下角
        giftIv.setLayoutParams(params);
        if (isBeauty) {
            int randomValue = currentIndex;
            if (currentIndex == listData.size() - 1)
                currentIndex = 0;
            else
                currentIndex++;
            giftIv.setTag(listData.get(randomValue).getStrID());
            Glide.with(getContext()).asBitmap()
                    .load(listData.get(randomValue).getStrImgUrl1())
                    .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                    .transform(new GlideCircleWithBorder(getContext(), 2, Color.parseColor("#ffffff")))
                    .into(giftIv);
            giftIv.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
//                isDetached = true;
                    if (onCommonCallBack != null) {
                        onCommonCallBack.onAchieve(view.getTag().toString(), "", 0);

                    }
                }
            });
        } else {
            giftIv.setImageResource(R.mipmap.icon_xb_nx);
        }


//        Glide.with(getContext()).load(strImgUrl).into(giftIv);
        addView(giftIv);
        addAnimator(giftIv);//添加动画效果，动画分两部分，第一部分是产生图片时缩放和透明度，第二部是移动图片再进行透明度变化
    }

    /**
     * 生出气泡的动画
     *
     * @param iv
     */
    private void addAnimator(final ImageView iv) {

        //点击的时候，让图片经过放大，缩放效果，之后再开始沿着贝塞尔曲线的轨迹移动
        ObjectAnimator alpha = ObjectAnimator.ofFloat(iv, "alpha", 0.3f, 1f);
        ObjectAnimator scaleX = ObjectAnimator.ofFloat(iv, "scaleX", 0.2f, 1f);
        ObjectAnimator scaleY = ObjectAnimator.ofFloat(iv, "scaleY", 0.2f, 1f);
        AnimatorSet set = new AnimatorSet();
        set.setDuration(1000);
        set.playTogether(alpha, scaleX, scaleY);
//        set.playTogether(alpha);
        set.setTarget(iv);
        set.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
//                set.setupEndValues();
                //设置贝塞尔曲线移动效果
                ValueAnimator va = getValueAnimator(iv);//第二部分动画
                va.start();
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        set.start();
    }

    //初始化贝塞尔曲线的4个点
    private void initPointF(ImageView iv) {
        int randomX = (int) (screenWidth * new Random().nextDouble());
        MarginLayoutParams lp = (MarginLayoutParams) iv.getLayoutParams();

        int bottomM = lp.bottomMargin;
        try {
//        p0 = new PointF(screenWidth / 2 - 0 - mDrawableWidth, screenHeight - 60 - mDrawableHeight);//起点是初始化时的点
//            p0 = new PointF(Math.abs(randomX), screenHeight - 60 - mDrawableHeight);//起点是初始化时的点
            p0 = new PointF(iv.getLeft() + iv.getWidth() * 0 / 2, iv.getBottom() - bottomM - iv.getHeight() / 2 - DpUtil.dp2px(10));//起点是初始化时的点
            p1 = new PointF(iv.getLeft() + iv.getWidth() * 0 / 2, Math.abs(mRandom.nextInt((int) p0.y)));//第一个控制点必须要在起始点的上方
            p2 = new PointF(iv.getLeft() + iv.getWidth() * 0 / 2, Math.abs(mRandom.nextInt((int) p1.y)));//第二个控制点必须在第一个点的上方
            p3 = new PointF(Math.abs(mRandom.nextInt(screenWidth) / 2), -mDrawableHeight);//终点在屏幕的最顶部0-图片的高度

        } catch (Exception e) {
            p0 = new PointF(Math.abs(randomX), screenHeight - 60 - mDrawableHeight);//起点是初始化时的点
            p1 = new PointF(Math.abs(screenWidth / 2), Math.abs(mRandom.nextInt((int) p0.y)));//第一个控制点必须要在起始点的上方
            p2 = new PointF(Math.abs(screenWidth / 2), Math.abs(mRandom.nextInt((int) p1.y)));//第二个控制点必须在第一个点的上方
            p3 = new PointF(Math.abs(screenWidth / 2), -mDrawableHeight);//终点在屏幕的最顶部0-图片的高度
            e.printStackTrace();
        }
    }


    /**
     * 自定义估值器计算图片移动的轨迹
     * 计算公式参考贝塞尔曲线3阶计算公式
     * 自定义估值器的方法可百度搜索
     * 其中估值器定义返回的结果为PointF
     */
    public class BezierEvaluator implements TypeEvaluator<PointF> {
        private PointF p1, p2;

        public BezierEvaluator(PointF p1, PointF p2) {
            this.p1 = p1;
            this.p2 = p2;
        }

        @Override
        public PointF evaluate(float t, PointF p0, PointF p3) {
            PointF point = new PointF();
            point.x = p0.x * (1 - t) * (1 - t) * (1 - t) //
                    + 3 * p1.x * t * (1 - t) * (1 - t)//
                    + 3 * p2.x * t * t * (1 - t)//
                    + p3.x * t * t * t;//

            point.y = p0.y * (1 - t) * (1 - t) * (1 - t) //
                    + 3 * p1.y * t * (1 - t) * (1 - t)//
                    + 3 * p2.y * t * t * (1 - t)//
                    + p3.y * t * t * t;//
            return point;
        }
    }

    private ValueAnimator getValueAnimator(final ImageView iv) {
        initPointF(iv);
        BezierEvaluator bezierEvaluator = new BezierEvaluator(p1, p2);
        ValueAnimator va = ValueAnimator.ofObject(bezierEvaluator, p0, p3);
        va.setDuration(new Random().nextInt(2000) + 6000);
        va.setTarget(iv);
        Animation animationScale = AnimationUtils.loadAnimation(getContext(), R.anim.scale_animation);
        iv.startAnimation(animationScale);//開始动画
        va.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                //改变imageview位置实现移动效果
                PointF point = (PointF) animation.getAnimatedValue();
                iv.setX(point.x);
                iv.setY(point.y);
                if (animation.getAnimatedFraction() > 0.80) {
                    float projess = (1 - animation.getAnimatedFraction()) / 0.2f;
                    iv.setScaleX(projess);
                    iv.setScaleY(projess);
                    if (animation.getAnimatedFraction() > 0.9) {
//                        iv.setScaleX(projess);
//                        iv.setScaleY(projess);
                        iv.setAlpha(projess);

                    }
                } else {
                    iv.setAlpha(1.0f);
                }


//                iv.setAlpha(1 - animation.getAnimatedFraction());

            /*    Animation animationScale = new ScaleAnimation(0.8f, 1.5f, 0.8f, 1.5f);
                animationScale.setDuration(500);//动画时间
                animationScale.setRepeatCount( 100);//动画的反复次数
                animationScale.setRepeatMode(Animation.REVERSE);//动画的反复次数
                animationScale.setFillAfter(true);//设置为true，动画转化结束后被应用
                iv.startAnimation(animationScale);//開始动画*/


                //动画结束移除imageview
                if (animation.getAnimatedFraction() >= 1) {
                    removeView(iv);
                }
            }
        });
        return va;
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();

        startBubbleSync();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        stopBubbleSync();
    }

    public void showBubble() {
        isViewBackground = false;
        startBubbleSync();
    }

    public void hideBubble() {
        isViewBackground = true;
        stopBubbleSync();


    }
}
